package com.kk.xhr.admin.biz.impl;

import com.kk.xhr.admin.biz.IWorkTimeBizService;
import com.kk.xhr.admin.controller.request.WorkTimeAddRequest;
import com.kk.xhr.admin.controller.vo.WorkTimeVO;
import com.kk.xhr.common.RedisConstant;
import com.kk.xhr.model.entity.WorkTime;
import com.kk.xhr.model.service.IWorkTimeService;
import com.kk.xhr.util.DateUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * @author kkmystery
 * @version 1.0 2021/3/23
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
public class WorkTimeBizServiceImpl implements IWorkTimeBizService {
    private final IWorkTimeService workTimeService;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public WorkTimeVO query() {
        LocalDate localDate = LocalDate.now();
        WorkTimeVO vo = (WorkTimeVO) redisTemplate.opsForValue().get(RedisConstant.WORK_TIME_CACHE);
        if (null == vo) {
            WorkTimeVO workTimeVO = workTimeService.query().map(entity -> WorkTimeVO.builder()
                .id(entity.getId())
                .earlyBegin(DateUtil.toMilliTimeStamp(LocalDateTime.of(localDate, entity.getEarlyBegin())))
                .earlyEnd(DateUtil.toMilliTimeStamp(LocalDateTime.of(localDate, entity.getEarlyEnd())))
                .lateBegin(DateUtil.toMilliTimeStamp(LocalDateTime.of(localDate, entity.getLateBegin())))
                .lateEnd(DateUtil.toMilliTimeStamp(LocalDateTime.of(localDate, entity.getLateEnd())))
                .duration(entity.getDuration())
                .flexDuration(entity.getFlexDuration())
                .build()).get();
            redisTemplate.opsForValue().set(RedisConstant.WORK_TIME_CACHE, workTimeVO);
            return workTimeVO;
        }
        return vo;
    }

    @Override
    public void modify(Integer id, WorkTimeAddRequest request) {
        workTimeService.modify(new WorkTime()
            .withId(id)
            .withEarlyBegin(DateUtil.from(request.getEarlyBegin()).toLocalTime())
            .withEarlyEnd(DateUtil.from(request.getEarlyEnd()).toLocalTime())
            .withLateBegin(DateUtil.from(request.getLateBegin()).toLocalTime())
            .withLateEnd(DateUtil.from(request.getLateEnd()).toLocalTime())
            .withDuration(request.getDuration())
            .withFlexDuration(request.getFlexDuration())
        );
        redisTemplate.delete(RedisConstant.WORK_TIME_CACHE);
    }
}
